package com.sjtu.config;

import com.google.gson.Gson;
import com.sjtu.service.LoginTokenService;
import com.sjtu.web.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * nerine
 * 2/7/2020
 */
@Component
public class TokenCheckFilter implements Filter {
    @Autowired
    private LoginTokenService loginTokenService;
    @Autowired
    private Gson gson;

    public static final String TOKEN_HEADER = "LOGIN-TOKEN";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String userId = request.getHeader(AdminHandlerFilter.OPERATOR_ID);
        String token = request.getHeader(TOKEN_HEADER);
        if(!loginTokenService.checkTokenIsValid(userId, token)) {
            Result result = new Result(Result.ResultCode.INVALID_IDENTITY, "token is expired", null);
            servletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            servletResponse.getWriter().write(gson.toJson(result));
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
